<template>
  <div class="app-container">
    <h3 class="title">标码管理</h3>
    <!-- {{ search }} -->
    <div v-if="setPermissionBtn('/code/findList', searchBtn)" class="inputBox">
      <el-input v-model="search.ruleNumber" class="input" placeholder="请输入规则编号" />
      <el-select v-model="search.traceabilityGoodsId" class="input" placeholder="请选择商品类型">
        <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>
      <el-input v-model="search.goodsName" class="input" placeholder="请输入商品名称查询" />
      <el-date-picker
        v-model="search.startTime"
        class="startDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="search.endTime"
        class="endDate"
        type="date"
        value-format="yyyy-MM-dd"
        placeholder="选择结束日期"/>
      <el-select v-model="search.status" class="" placeholder="请选状态">
        <el-option label="停用" value="0" />
        <el-option label="启用" value="1" />
      </el-select>
      <el-button type="primary" class="ml10" @click="toSearch">{{ searchBtn.btnName }}</el-button>
      <el-button type="primary" @click="toReset">重置</el-button>
    </div>

    <el-button v-if="setPermissionBtn('/code/add', addBtn)" type="primary" class="addBtn" @click="add()">{{ addBtn.btnName }}</el-button>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中请稍后"
      border
      fit
      highlight-current-row>
      <template slot="empty">
        <div class="noData">暂无数据</div>
      </template>
      <el-table-column label="规则编号" width="130">
        <template slot-scope="scope">
          {{ scope.row.ruleNumber }}
        </template>
      </el-table-column>
      <el-table-column label="溯源商品类型">
        <template slot-scope="scope">
          {{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <el-table-column label="溯源商品名称">
        <template slot-scope="scope">
          {{ scope.row.goodName }}
        </template>
      </el-table-column>
      <el-table-column label="编码规则">
        <template slot-scope="scope">
          {{ scope.row.codingRules }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="100">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="状态">
        <template slot-scope="scope">
          <span v-if="scope.row.status === 0">停用</span>
          <span v-if="scope.row.status === 1">启用</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="400">
        <template slot-scope="scope">
          <el-button
            v-if="setPermissionBtn('/code/generateCode', scope.row)"
            :disabled="scope.row.status===0"
            size="mini"
            value="生成标码"
            type="success"
            @click="createCode(scope.row, scope.$index)">{{ scope.row.btnName }}</el-button>
          <el-button
            v-if="setPermissionBtn('edit', scope.row)"
            :disabled="scope.row.status===1"
            size="mini"
            value="编辑"
            type="primary"
            @click="edit(scope.row, scope.$index)">编辑</el-button>
          <el-button
            v-if="setPermissionBtn('enable/disable', scope.row)"
            :type="scope.row.status == 0?'success':'danger'"
            size="mini"
            value="启用/停用"
            @click="updateStatus(scope.row.id, scope.row.status)"
            v-html="splitName(scope.row.btnName, scope.row.status)"/>
          <!-- <el-button
            v-if="scope.row.status===1"
            size="mini"
            value="停用"
            type="danger"
            @click="updateStatus(scope.row.id, 0)">停用</el-button>
          <el-button
            v-if="scope.row.status===0"
            size="mini"
            value="启用"
            type="success"
            @click="updateStatus(scope.row.id, 1)">启用</el-button> -->
          <el-button
            v-if="setPermissionBtn('del', scope.row)"
            :disabled="scope.row.status===1"
            value="删除"
            size="mini"
            type="danger"
            @click="del(scope.row.id)">{{ scope.row.btnName }}</el-button>
          <el-button
            size="mini"
            type="warning"
            @click="record(scope.row.id)">记录</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="fetchData" />
    <AddCode
      :my-index.sync="codeIndex"
      :settings-visible.sync="codeVisible"
      :dialog-data.sync="codeData"
      :setting-mode="'code'"
      @updataParent="submitFn"
    />
    <AddCode
      :my-index.sync="createCodeIndex"
      :settings-visible.sync="createCodeVisible"
      :dialog-data.sync="createCodeData"
      :setting-mode="'createCode'"
      @updataParent="createCodeFn"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

import { Message } from 'element-ui'
import { getLocalUid, setLocalUid, getLocalId, setLocalId } from '@/utils/uid'
import { getPermission } from '@/api/permission'
import { getLocalUserName, setLocalUserName } from '@/utils/uid'
import { getCodeList, addCode, updateCode, delCode, enableAndDisableCode, createCode } from '@/api/source'
import { categoryQuery } from '@/api/product'
import AddCode from '@/components/source/AddCode'
let that
export default {
  components: { Pagination, AddCode },
  filters: {
    goodsType(num) {
      // console.log('categoryList:', this.categoryList)
      console.log('categoryList:', that.categoryList)
      that.categoryList.forEach(item => {
        if (item.id === num) {
          console.log(item.id)
          return item.name
        }
      })
    }
  },
  data() {
    return {
      addBtn: {}, // 显示按钮的变量
      searchBtn: {},
      // visible: false,
      remarkProptVisible: false,
      remarkProptList: [],
      remarkProptIndex: -1,
      userName: '',
      userType: -1,
      categoryList: [],
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 0,
        pageSize: 10
      },
      search: {
        traceabilityGoodsId: '',
        ruleNumber: '',
        goodsName: '',
        startTime: '',
        endTime: '',
        status: ''
      },
      dialogTableVisible: false,
      detailIndex: -1,
      permissionShow: false, // 权限数据未到达之前按钮隐藏

      codeVisible: false, // 新增标码规则弹窗
      codeIndex: -1,
      codeData: {},

      createCodeVisible: false, // 生成标码弹窗
      createCodeIndex: -1,
      createCodeData: {}

      // permissionList: [] // 权限数据列表
    //   remarkVisible: false,
    //   remarkIndex: -1,
    //   remarkList: [],

    //   logistics: false, // 物流弹窗
    //   logisticsIndex: -1,
    //   orderSn: '',

    //   sendGoodsVisible: false, // 发货弹窗
    //   sendGoodsIndex: -1,
    //   sendGoodsData: {}

    }
  },
  computed: {
    // 权限按钮 computed
    setPermissionBtn() {
      return function(str, row) {
        let index = -1
        const buttonList = this.$store.getters.button
        index = buttonList.findIndex(item => item.value === str)
        // console.log(index)
        if (index !== -1) {
          row.btnName = buttonList[index].name
          return true
        } else {
          return false
        }
      }
    },
    // 用于 停用/启用  上架/下架 按钮的显示
    splitName() {
      return function(name, status) {
        const nameArr = name.split('/')
        if (status === 0) {
          return nameArr[0]
        } else {
          return nameArr[1]
        }
      }
    }
  },
  watch: {
    'permissionList'(newVal) {
      this.permissionList = newVal
      this.permissionShow = true
    }
  },
  beforeCreate() {
    that = this
  },
  created() {
    this.getUserType()
    this.getCategory()
    this.fetchData()
    // console.log('userType:', this.userType)
    // this.getPermissonFn()
  },
  mounted() {
    this.getPermissonFn() // 获取按钮权限 vuex的button
  },
  methods: {
    // 权限数据的获取
    // getPermissonFn() {
    //   const id = getLocalId()
    //   const uid = getLocalUid()
    //   const data = { uid }
    //   getPermission(id, data).then(res => {
    //     console.log('权限结果', res)
    //     if (res.code === '200') {
    //       this.permissionList = res.data
    //       // console.log('权限名称：', this.getPermissionName(this.permissionList))
    //     } else {
    //       Message.error(res.message + '-' + res.data)
    //     }
    //   })
    // },
    createCode(row, index) {
      this.createCodeVisible = true
      this.createCodeData = row
      this.createCodeIndex = index
    },
    createCodeFn(val) {
    //   createCode(val)
    //   Message.success('正在下载')
    },
    submitFn(val) {
      console.log('this.codeIndex:', this.codeIndex)
      if (this.codeIndex > -1) {
        console.log('编辑标码规则：：：', val)
        updateCode(val).then(res => {
          if (res.code === '200') {
            Message.success('编辑成功')
            this.fetchData()
          } else {
            Message.error(res.message + '-' + res.data)
          }
        })
      } else { // 新增
        addCode(val).then(res => {
          if (res.code === '200') {
            Message.success('新增成功')
            this.fetchData()
          } else {
            Message.error(res.message + '-' + res.data)
          }
        })
      }
    },
    record(id) {
      this.$router.push({
        path: 'createCode',
        query: {
          id
        }
      })
      // this.router.push('sourceCode')
    },
    add() {
      this.codeVisible = true
      // codeIndex
      // codeData
    },
    updateStatus(id, type) {
      const strAsk = type === 1 ? '是否停用？' : '是否启用？'
      const str = type === 0 ? '已停用' : '已启用'
      this.$confirm(strAsk, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        type === 0 ? type = 1 : type = 0
        const data = { status: type, id }
        enableAndDisableCode(data).then(res => {
          if (res.code === '200') {
            Message.success(str)
            this.fetchData()
          } else {
            Message.error(res.message + res.data)
          }
        })
      })
    },
    edit(row, index) {
      this.codeVisible = true
      this.codeData = row
      this.codeIndex = index
    },
    del(id) {
      this.$confirm('您确定删除此标码规则？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        delCode({ id }).then(res => {
          if (res.code === '200') {
            Message.success('已删除')
            this.fetchData()
          } else {
            Message.error(res.message + '-' + res.data)
            this.listLoading = false
          }
        })
      })
    },
    // 获取所有分类信息
    getCategory() {
      categoryQuery().then(res => {
        console.log('获取所有分类信息:', res)
        if (res.code === '200') {
          this.categoryList = res.data
        }
      })
    },
    getUserType() {
      switch (getLocalUserName()) {
        case 'admin':
          this.userType = 1
          break;
        case 'sale':
          this.userType = 2
          break;
        case 'casher':
          this.userType = 3
          break;
      }
    },
    // 查询
    toSearch() {
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime && this.search.startTime.indexOf(' 00:00:00') === -1) this.search.startTime += ' 00:00:00'
      if (this.search.endTime && this.search.endTime.indexOf(' 23:59:59') === -1) this.search.endTime += ' 23:59:59'
      if (this.search.startTime && this.search.endTime) {
        const start = new Date(this.search.startTime).getTime();
        const end = new Date(this.search.endTime).getTime();
        if (start > end) {
          Message.error('结束时间必须大于开始时间')
          return false
        }
      }
      if (this.search.startTime) this.search.startTime
      if (this.search.endTime) this.search.endTime
      this.listLoading = true
      console.log(this.search)
      const newData = this.objectCon(this.listQuery, this.search)
      getCodeList(newData).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          this.total = response.data.total
        } else {
          Message.error(response.message + '-' + response.data)
        }
        setTimeout(() => {
          this.listLoading = false
        }, 1.5 * 1000)
      })
    },
    // 重置
    toReset() {
      this.search.traceabilityGoodsId = ''
      this.search.ruleNumber = ''
      this.search.goodsName = ''
      this.search.startTime = ''
      this.search.endTime = ''
      this.search.status = ''
    },
    /*
      已取消 -100
      待付款 0
      已付款(待发货)100
      已发货(待收货)200
      已收货 300
      申请退款 400
      拒绝退款 410
      (买家)待发货(同意退款) 420
      (买家)已发货 430
      (商家)已收货 440
      已退款 450
      已完成 500
      */
    fetchData() {
      this.listLoading = true
      getCodeList(this.listQuery).then(response => {
        if (response.code === '200') {
          this.list = response.data.list
          console.log('订单数据：', this.list)
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 0.5 * 1000)
        } else {
          this.listLoading = false
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
  .inputBox{
    div{ margin-bottom: 10px;}
    .input:nth-of-type(1){ width: 200px }
    .input:nth-of-type(2){ width: 180px }
    .input:nth-of-type(3){ width: 160px }
    .input:nth-of-type(4){ width: 180px }
    .startDate, .endDate{ width: 180px }
    .input:nth-of-type(7){width:140px}
  }
  .addBtn{
      margin-bottom: 20px;
  }
</style>
